package com.mic.security.web.authentication;

import java.util.List;
import java.util.Set;
import java.util.HashSet;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.mic.security.dao.LoginUserDAO;
import com.mic.security.dao.RoleDAO;
import com.mic.security.model.LoginUser;
import com.mic.security.model.Role;

/**
 * spring security��ȫ���ƣ����ڴ���ݿ�����û�
 * 
 * @author mulan
 * 
 */
public class BasicUserDetailsServiceImpl implements UserDetailsService {

	/**
	 * ��¼�û����ʽӿ�
	 */
	private LoginUserDAO loginUserDAO;

	private RoleDAO roleDAO;

	/**
	 * ����ݿ��ȡ��¼�û���Ϣ
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		LoginUser loginUser = null;
		try {
			// ����ݿ��ȡ�û�
			loginUser = loginUserDAO.loadUserByUsername(username);
			// �û�������
			if (loginUser == null) {
				throw new UsernameNotFoundException("�û�" + username + " ������!");
			}
			String userid = loginUser.getId();
			//���õ�½�û��Ľ�ɫ
			List<Role> roles = roleDAO.listRolesByUserId(userid);
			if(roles==null||roles.size() == 0){
				throw new UsernameNotFoundException("�û�" + username + " ������!");
			}
			loginUser.setRoles(roles);
			// ���õ�¼�û���Ȩ��
			//Set<GrantedAuthority> authorities = Sets.newHashSet();
			Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
			for(Role role: roles){
				authorities.add(new SimpleGrantedAuthority(role.getName()));
			}
			loginUser.setAuthorities(authorities);
		} catch (Exception e) {
			// 
			e.printStackTrace();
		}
		// ���ص�¼�û�
		return loginUser;
	}

	/*
	 * Getter and Setter
	 */
	public LoginUserDAO getLoginUserDAO() {
		return loginUserDAO;
	}

	public void setLoginUserDAO(LoginUserDAO loginUserDAO) {
		this.loginUserDAO = loginUserDAO;
	}

	public RoleDAO getRoleDAO() {
		return roleDAO;
	}

	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	
}

